# coding=utf-8
# 代码文件：chapter1/ch1.14.2-1.py
import datetime as dt

f_name = 'data/test1.txt'

''' read_date_from_file函数从文件中读取字符串并转换为日期。'''


def read_date_from_file(filename):
    try:
        file = open(filename)           # 打开文件过程有可能引发FileNotFoundError异常
        in_date = file.read()           # 读取文件内容可能引发OSError异常
        in_date = in_date.strip()       # strip函数删除字符串前前后的空格
        date = dt.datetime.strptime(in_date, '%Y-%m-%d')
        return date
    except ValueError as e:
        print('处理ValueError异常')
    except FileNotFoundError as e:
        print('处理FileNotFoundError异常')
    except OSError as e:
        print('处理OSError异常')
    finally:
        file.close()                    # 关闭文件


if __name__ == '__main__':
    date = read_date_from_file(f_name)
    print('日期 = {0}'.format(date))
